//
//  GalleryViewer.swift
//  Automobile
//
//  Created by erkebulan elzhan on 9/3/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit
import SDWebImage

final class GalleryViewer: UIView {
    
    // MARK: - Outlets
    
    private lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.isPagingEnabled = true
        scrollView.contentSize = CGSize(width: CGFloat(images.count) * self.frame.width, height: frame.height)
        scrollView.maximumZoomScale = 5
        scrollView.minimumZoomScale = 1
        scrollView.delegate = self
        return scrollView
    }()

    lazy var backBtn: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "cancel"), for: .normal)
        button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 13.5, bottom: 10, right: 13.5)
        return button
    }()
    
    private lazy var titleLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = .systemFont(ofSize: 20, weight: .semibold)
        lbl.textColor = .greyColor
        lbl.text = "Фото машины"
        return lbl
    }()
    
    // MARK: - Props
    
    private var images: [String] = []

    private var scrollIndex: Int?
    
    public func setProps (images: [String], index: Int? = nil) {
        self.titleLbl.text = "Фото 1 из \(images.count)"
        self.images = images
        self.scrollIndex = index
        self.addImages()
    }
    
    private var previousPage: Int = 0
    
    // MARK: - Init
    
    init () {
        super.init(frame: .zero)
        self.addViews()
        AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.portrait, andRotateTo: UIInterfaceOrientation.portrait)
    }
    
    deinit {
        AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.all)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.setContentSize()
    }
    
    // MARK: - UI
    
    private func setContentSize () {
        let postWidth = (self.frame.width) * CGFloat(images.count)
        scrollView.contentSize = CGSize(width: postWidth, height: scrollView.frame.height)
        
        if scrollIndex != nil {
            var rect = self.scrollView.frame
            let xPosition = self.frame.width * CGFloat(scrollIndex ?? 0)
            rect.origin = CGPoint(x: xPosition, y: 0)
            self.scrollView.scrollRectToVisible(rect, animated: true)
            scrollIndex = nil
        }
    }
    
    private func addImages () {
        var leading = scrollView.snp.leading
        var firstItem = true
        
        for i in 1...images.count {
            let postItem = GalleryItem(imageURL: images[i - 1])
            scrollView.addSubview(postItem)
            
            postItem.snp.makeConstraints { (make) in
                make.width.equalTo(self.snp.width).offset(-32)
                make.height.equalToSuperview()
                make.leading.equalTo(leading).offset(firstItem ? 16 : 32)
            }
            
            firstItem = false
            leading = postItem.snp.trailing
        }
    }
    
    private func addViews () {
        backgroundColor = .black
        addSubview(scrollView)
        addSubview(titleLbl)
        addSubview(backBtn)
        
        backBtn.snp.makeConstraints { (make) in
            make.width.height.equalTo(40)
            make.leading.equalToSuperview().inset(10.5)
            make.top.equalToSuperview().inset(32)
        }
        
        titleLbl.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(backBtn)
        }
        
        scrollView.snp.makeConstraints { (make) in
            make.top.equalTo(backBtn.snp.bottom).offset(8)
            make.leading.bottom.trailing.equalToSuperview()
        }
    }
}

extension GalleryViewer: GalleryItemDelegate {
    func galleryViewDidEnableScroll() {
        self.scrollView.isScrollEnabled = false
    }
    
    func galleryViewDidDisableScroll() {
        self.scrollView.isScrollEnabled = true
    }
}


extension GalleryViewer: UIScrollViewDelegate {

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let pageWidth: CGFloat = scrollView.frame.width
        let fractionalPage: CGFloat = scrollView.contentOffset.x / pageWidth
        let page = lround(Double(fractionalPage))
        if page != previousPage {
            self.titleLbl.text = "Фото \(page + 1) из \(images.count)"
            previousPage = page
        }
    }
    
}


protocol GalleryItemDelegate {
    func galleryViewDidEnableScroll()
    func galleryViewDidDisableScroll ()
}

final class GalleryItem: UIView {
    
    private lazy var scrollView: ImageScrollView = {
        let scrollView = ImageScrollView()
        scrollView.setup()
        return scrollView
    }()

    
    var delegate: GalleryItemDelegate!
    
    init (imageURL: String) {
        super.init(frame: .zero)
        self.addSubview(scrollView)
        
        let url = URL(string: imageURL)
        
        SDWebImageManager.shared.loadImage(with: url, options: [], progress: nil) { (image, error, _, _, isSuccess, url) in
            if error == nil {
                self.scrollView.display(image: image!)
            }
        }
    
        scrollView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        scrollView.zoomScale = scrollView.minimumZoomScale
        scrollView.contentSize = scrollView.frame.size
    }
}


